package com.lbs.jiepiaisi.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.AroundLocationActivity;
import com.lbs.jiepiaisi.activity.DownLoadDialogActivity;
import com.lbs.jiepiaisi.activity.NewsDetailActivity;
import com.lbs.jiepiaisi.activity.NewsMoreActivity;
import com.lbs.jiepiaisi.activity.PoiAroundSearchActivity;
import com.lbs.jiepiaisi.activity.WeiZhangChaXunActivity;
import com.lbs.jiepiaisi.adapter.NewsListAdapter;
import com.lbs.jiepiaisi.base.BaseFragment;
import com.lbs.jiepiaisi.bean.NewsEntity;
import com.lbs.jiepiaisi.service.DownloadService;
import com.lbs.jiepiaisi.utils.ACache;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;

import com.lbs.jiepiaisi.utils.IntentUtil;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.utils.UrlUtil;
import com.lbs.jiepiaisi.view.CycleShowView;
import com.lbs.jiepiaisi.view.NoScrollListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 五图滚动
 */
public class ServiceFragment extends BaseFragment {
    CycleShowView cycleView;
    String[] imageUrls = new String[]{
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528776372505&di=7251eef9d6922ddb2f69e79e366f9468&imgtype=0&src=http%3A%2F%2Fpicture.ik123.com%2Fuploads%2Fallimg%2F160107%2F3-16010G41S2.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528776592897&di=4af16e296865203312a94538e0c2f764&imgtype=0&src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F5%2F57a820b1860d0.jpg",
            "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1528777297277&di=8d84f43fe1b33f767177fd3469b9ba07&imgtype=0&src=http%3A%2F%2Fimg4.xiazaizhijia.com%2Fwalls%2F20150115%2F1440x900_67930961334368a.jpg"
    };

    private TextView tv_version;

    //违章查询
    private Button btn_weizhangchaxun;
    //呼叫代驾
    private Button btn_get_driver;
    //附近停车
    private Button btn_around_driver;
    //周边导航
    private Button btn_around_get;
    //加油站
    private Button btn_add_oil;
    //汽车维修
    private Button btn_fix_bus;

    //新闻推荐
    private NoScrollListView lv_news_list;

    private NewsReceiver newsReceiver;

    private ScrollView scrollView;

    ACache aCache;

    List<NewsEntity.Result.Data> listItem;

    private TextView tv_news_more;

    private RelativeLayout mNewsRel;

    @Override
    public View initView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_service, null);

        newsReceiver = new NewsReceiver();

        getActivity().getApplicationContext().registerReceiver(newsReceiver, new IntentFilter(Constant.NEWS_FLAG));

        return view;
    }

    @Override
    protected void getExtras(View view) {
    }

    @Override
    protected void findView(View view) {
        //滚动广告
        cycleView = (CycleShowView) view.findViewById(R.id.cycle_view);
        cycleView.setData(imageUrls);
        cycleView.startPlay();
        cycleView.setMyPageOnClickItemListener(new CycleShowView.MyPageOnClickItemListener() {
            @Override
            public void curSelect(int position) {
                //Toast.makeText(getContext(), position + "", Toast.LENGTH_SHORT).show();
            }
        });
        tv_version = view.findViewById(R.id.tv_version);
        tv_version.setText("当前版本："+getVersionName());
        //违章查询
        btn_weizhangchaxun = (Button) view.findViewById(R.id.btn_weizhangchaxun);
        //呼叫代驾
        btn_get_driver = (Button) view.findViewById(R.id.btn_get_driver);
        //附近停车
        btn_around_driver = (Button) view.findViewById(R.id.btn_around_driver);
        //周边导航
        btn_around_get = (Button) view.findViewById(R.id.btn_around_get);
        //加油站
        btn_add_oil = (Button) view.findViewById(R.id.btn_add_oil);
        //汽车维修
        btn_fix_bus = (Button) view.findViewById(R.id.btn_fix_bus);
        //新闻推荐
        lv_news_list = (NoScrollListView) view.findViewById(R.id.lv_news_list);
        //更多新闻
        tv_news_more = (TextView) view.findViewById(R.id.tv_news_more);
        //咨询推荐
        mNewsRel = (RelativeLayout) view.findViewById(R.id.rel_news);

        scrollView = (ScrollView)view.findViewById(R.id.scrollView);

        // 2019.新闻资讯请求
//        aCache = ACache.get(getActivity());
//        String newsString = aCache.getAsString(Constant.NEWS_CACHE);
//        if (newsString == null) {
//            NewsBiz newsBiz = new NewsBiz();
//            newsBiz.getNews(Constant.NEWS_TYPE_TOP, Constant.NEWS_FLAG);
//        } else {
//            NewsBiz newsBiz = new NewsBiz();
//            newsBiz.getNews(Constant.NEWS_TYPE_TOP, Constant.NEWS_FLAG);
////            listItem = handleList(NewsParser.parser(newsString).getResult().getData());
////            newsListAdapter = new NewsListAdapter(getActivity(), listItem);
////            lv_news_list.setAdapter(newsListAdapter);
////            scrollView.scrollTo(0,0);
//        }

        try{
            //检查更新
            VersionParams.Builder builder = new VersionParams.Builder()
                    .setRequestUrl(UrlUtil.CHECK_VERSION)
                    .setForceRedownload(true)
                    .setShowNotification(true)
                    .setService(DownloadService.class);
            builder.setCustomDownloadActivityClass(DownLoadDialogActivity.class);
            AllenChecker.startVersionCheck(getActivity(), builder.build());
        }catch (Exception e){

        }
    }

    private String getVersionName() {
        //获取packagemanager的实例
        PackageManager packageManager = mContext.getPackageManager();
        //getPackageName当前类的包名，0代表是获取版本信息
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        String version = packageInfo.versionName;
        return version;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                break;
            default:
                break;
        }
    }

    @Override
    protected void setListener(View view) {
        //违章查询
        btn_weizhangchaxun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ButtonUtil.isFastClick()) {
                    IntentUtil.gotoActivity(getActivity(), WeiZhangChaXunActivity.class, false);
                }
            }
        });
        //呼叫代驾
        btn_get_driver.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                IntentUtil.gotoActivity(getActivity(), WeiZhangGaoFaDiAcitivity.class, false);
                ToastUtil.show("暂未开通，敬请期待");
                return;
//                if (ButtonUtil.isFastClick()) {
//                    IntentUtil.gotoActivity(getActivity(), GetDriverActivity.class, false);
//                }
            }
        });
        //附近停车
        btn_around_driver.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), PoiAroundSearchActivity.class);
                intent.putExtra("keyWord", "停车场");
                startActivity(intent);
            }
        });
        //周边导航
        btn_around_get.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), AroundLocationActivity.class);
                startActivity(intent);
            }
        });
        //加油站
        btn_add_oil.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), PoiAroundSearchActivity.class);
                intent.putExtra("keyWord", "加油站");
                startActivity(intent);
            }
        });
        //汽车维修
        btn_fix_bus.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), PoiAroundSearchActivity.class);
                intent.putExtra("keyWord", "汽车维修");
                startActivity(intent);
            }
        });
        //点击新闻
        lv_news_list.setOnItemClickListener((parent, view1, position, id) -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                intent.putExtra("news", listItem.get(position));
                startActivity(intent);
            }
        });
        //更多新闻
        tv_news_more.setOnClickListener(v -> {
            if (ButtonUtil.isFastClick()) {
                Intent intent = new Intent(getActivity(), NewsMoreActivity.class);
                startActivity(intent);
            }
        });


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getApplicationContext().unregisterReceiver(newsReceiver);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private NewsListAdapter newsListAdapter = null;

    //接收实时跟踪数据的广播
    class NewsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            NewsEntity newsEntity = (NewsEntity) intent.
                    getSerializableExtra(Constant.KEY_DATA);
            if (newsEntity != null && newsEntity.getError_code() == Constant.STATUS_OK && newsEntity.getResult() != null) {
                listItem = handleList(newsEntity.getResult().getData());
                aCache.put(Constant.NEWS_CACHE, new Gson().toJson(newsEntity), 60);
                newsListAdapter = new NewsListAdapter(getActivity(), listItem);
                lv_news_list.setAdapter(newsListAdapter);
                scrollView.scrollTo(0,0);
            } else {
                mNewsRel.setVisibility(View.GONE);
            }
        }
    }

    private List<NewsEntity.Result.Data> handleList(List<NewsEntity.Result.Data> source) {
        List<NewsEntity.Result.Data> output = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            if (source != null && source.size() > i) {
                output.add(source.get(i));
            }
        }
        return output;
    }
}